import fs from 'fs';
import replace from 'rollup-plugin-replace';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import json from 'rollup-plugin-json';
import sucrase from 'rollup-plugin-sucrase';
import typescript from 'rollup-plugin-typescript';
import pkg from './package.json';

const is_publish = !!process.env.PUBLISH;

export default [
	/* internal.[m]js */
	{
		input: `src/internal/index.js`,
		output: [
			{
				file: `internal.mjs`,
				format: 'esm',
				paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
			},
			{
				file: `internal.js`,
				format: 'cjs',
				paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
			}
		],
		external: id => id.startsWith('svelte/'),
		plugins: [{
			generateBundle(options, bundle) {
				const mod = bundle['internal.mjs'];
				if (mod) {
					fs.writeFileSync('src/compile/internal-exports.ts', `// This file is automatically generated\nexport default new Set(${JSON.stringify(mod.exports)});`);
				}
			}
		}]
	},

	/* compiler.js */
	{
		input: 'src/index.ts',
		plugins: [
			replace({
				__VERSION__: pkg.version
			}),
			resolve(),
			commonjs({
				include: ['node_modules/**']
			}),
			json(),
			is_publish
				? typescript({
					include: 'src/**',
					exclude: 'src/internal/**',
					typescript: require('typescript')
				})
				: sucrase({
					transforms: ['typescript']
				})
		],
		output: {
			file: 'compiler.js',
			format: is_publish ? 'umd' : 'cjs',
			name: 'svelte',
			sourcemap: true,
		},
		external: is_publish
			? []
			: id => id === 'acorn' || id === 'magic-string' || id.startsWith('css-tree')
	},

	/* motion.mjs */
	{
		input: `src/motion/index.js`,
		output: [
			{
				file: `motion.mjs`,
				format: 'esm',
				paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
			},
			{
				file: `motion.js`,
				format: 'cjs',
				paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
			}
		],
		external: id => id.startsWith('svelte/')
	},

	// everything else
	...['index', 'store', 'easing', 'transition', 'animate'].map(name => ({
		input: `${name}.mjs`,
		output: {
			file: `${name}.js`,
			format: 'cjs',
			paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
		},
		external: id => id !== `${name}.mjs`
	}))
];
